package model

import (
    "ginblog/model/response"
    "github.com/jinzhu/gorm"
)

type Option interface {
    Create() Code
}

type User struct {
    gorm.Model
    Username string `gorm:"type:varchar(20);not null" json:"username"`
    Password string `gorm:"type:varchar(20);not null" json:"password"`
    Role     int    `gorm:"type:int(11)" json:"role"`
    Avatar   string `gorm:"type:" json:"avatar"`
}

func (u *User) TableName() string {
    return "user"
}

func (u *User) CheckUser(p ...[]string) Code {
    db.Select("id").Where("username = ? ", u.Username).First(&u)
    if u.ID > 0 {
        return ERROR_USERNAME_USED
    }
    return SUCCESS
}

func (u *User) Create() Code {
    op := db.Create(u)
    if err := op.Error; err != nil {
        return DB_ERROR
    }
    if op.RowsAffected == 0 {
        return DB_OPTION_FAIL
    }

    return SUCCESS
}

func GetUsers(pageSize, pageNum int) (users []User, err error) {
    var (
        tatal int
    )
    err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users).Error
    db.Model(&User{}).Count(&tatal)
    if err != nil && err != gorm.ErrRecordNotFound {
        return
    }
    return users, nil
}

func GetUsersV2(pageSize, pageNum int) (p response.PageInfo, err error) {
    var (
        users []User
        tatal int
    )
    err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users).Error
    db.Model(&User{}).Count(&tatal)
    if err != nil && err != gorm.ErrRecordNotFound {
        return
    }
    p = response.PageInfo{
        List:  users,
        Total: tatal,
    }
    return p, nil
}
